<?php if(!defined('BASEPATH')) exit ('No direct script access allowed');

class Person extends public_controller
{
	
	public function __construct() {
		parent:: __construct();
		$this->template->set_layout('person_layout');
		//if(!$this->session->userdata('loginStatus')) redirect('landing');
		$this->load->model('member/member_model');
		//echo $this->session->userdata('loginStatus');
	}

	public function index(){
		if(!$this->session->userdata('loginStatus')) redirect('landing');

		$uri = $this->uri->segment(2);
		$uri = explode('-', $uri);
		$personId = $uri[0];
		$infoPerson = $this->person_model->get_person($personId);
		if(!empty($infoPerson)) {
			$this->current_person_id = $personId;
			$this->show_btn_upload = TRUE;

			$crumb = array(
				'Home'	=> base_url(),
				$infoPerson['name'] => ''
			);

			$this->template->title($infoPerson['name'], 'Dead project')
				->set_metadata('keywords', $infoPerson['name'])
	            ->set_metadata('description', $infoPerson['name'])
				->set('infoPerson', $infoPerson)
				->set('crumb', $crumb)
				->build('person/index');	
		} else {
			redirect('home');
		}
	}

	public function edit() {
		if(!$this->session->userdata('loginStatus')) redirect('landing');

		$this->template->set_layout('default');
		$uri = (int)$this->uri->segment(3);
		$oldImage = $this->input->post('old_photo');
		$infoPerson = $this->person_model->get_person($uri);
		if($infoPerson) {
			if($_POST) {
				$this->form_validation->set_rules('name', 'Name', 'required');
				$this->form_validation->set_rules('day_birth', 'Birthday', 'required');
				$this->form_validation->set_rules('day_death', 'Death day', 'required');
				$this->form_validation->set_rules('sl_country', 'Country', 'required');
				if($this->form_validation->run() === TRUE) {

					if(!empty($_FILES['photo_cover']['name']))
	                {
	                    $config['upload_path'] = './data_uploads/person/';
	                    $config['allowed_types'] = 'gif|jpg|png';
	                    $config['encrypt_name'] = TRUE;

	                    $this->load->library('upload', $config);

	                    if ( ! $this->upload->do_upload('photo_cover'))
	                    {
	                        echo $this->upload->display_errors();
	                        $image = $oldImage;
	                    } else {
	                    	if($oldImage !== "") @unlink($oldImage);
	                        $up = $this->upload->data();
	                        $image = 'data_uploads/person/' . $up['file_name'];

	                        $imageWidth = $up['image_width'];
	                        if($imageWidth > 150)
	                        {
	                            $this->load->library('image_lib');
	                            $config['image_library'] = 'GD2';
	                            $config['source_image'] = $up['full_path'];
	                            $config['quality'] = 75;
	                            $config['maintain_ratio'] = TRUE;
	                            $config['master_dim'] = 'auto';
	                            $config['width'] = 150;
	                            $config['height'] = 150;

	                            $this->image_lib->initialize($config);
	                            $this->image_lib->resize();
	                        }

	                    }
	                } else {
	                    $image = $oldImage;
	                }  

					$birthday = $this->input->post('day_birth');
					$deathday = $this->input->post('day_death');
					$arr = array(
						//'member_id'		=> $this->session->userdata('sess_memId'),
						'name'			=> $this->input->post('name'),
						'day_birth'		=> strtotime($this->input->post('day_birth')),
						'day_death'		=> strtotime($this->input->post('day_death')),
						'country'		=> $this->input->post('sl_country'),
						'state'			=> $this->input->post('sub_region'),
						'long_desc'		=> $this->input->post('desc'),
						'age'			=> $this->util->calculator_age($deathday, $birthday),
						'public'		=> $this->input->post('chk'),
						'photo_cover'	=> $image
					);
				}

					$this->db->update('person', $arr, array('id' => $uri));
					$this->session->set_flashdata('sess_Info', 'The person has been updated successfully');
					redirect('my-added');
			}

			$crumb = array(
				'Home'	=> base_url(),
				'Edit ' .$infoPerson['name'] => ''
			);

		} else {
			redirect('home');
		}


		$countries = $this->db->select('id, country')->get('regions')->result_array();
		$this->template->title('Edit Person')
			->set('countries', $countries)
			->set('infoPerson', $infoPerson)
			->set('crumb', $crumb)
			->build('add_person/edit');
	}

	public function upload_photo(){

		$person_id = (int)$_POST['personId'];
		$memId = (int)$_POST['memId'];
		$uploadDir = './data_uploads/person_photo/';        
        if(!is_dir($uploadDir)) {
            mkdir($uploadDir);
            chmod($uploadDir, 0777);
        }
        //$saveDirLarge = substr($uploadDir, 2).'/';

        $config['upload_path'] = $uploadDir;
        $config['allow_flash'] = TRUE;
        $config['allowed_types'] = '*';
        $config['max_size']    = '2048';
        //$config['max_width']  = '1024';
        //$config['max_height']  = '768';
        $config['encrypt_name'] = TRUE;
        $this->load->library('upload', $config);

        if (! $this->upload->do_upload('userfile')){
            echo ($this->upload->display_errors());                       
        } else {
            $dataUpload = $this->upload->data();
            $imgLarge = 'data_uploads/person_photo/'. $dataUpload['file_name'];
            list($width) = getimagesize($dataUpload['full_path']);
            $imageWidth = $dataUpload['image_width'];
            if($width > 530)
            {
                $this->load->library('image_lib');
                $config['image_library'] = 'GD2';
                $config['source_image'] = $dataUpload['full_path'];
                $config['quality'] = 75;
                $config['maintain_ratio'] = TRUE;
                $config['master_dim'] = 'auto';
                $config['width'] = 530;
                $config['height'] = 400;

                $this->image_lib->initialize($config);
                $this->image_lib->resize();
            }

            $arr_img = array(
                'photo' => $imgLarge,
                'person_id' => $person_id,
                'mem_id' => $memId
            );  

            $this->db->insert('photo_person', $arr_img);
            
            echo json_encode($this->upload->data());                   
        }  
	}

	public function loadListPhotoPerson(){
		$person_id = (int)$this->input->post('personId');
		$memId = $this->session->userdata('sess_memId');
		$sql = $this->db->select('id,photo')->get_where('photo_person', array('person_id' => $person_id, 'mem_id' => $memId))->result_array();

		if(count($sql)) {
			foreach($sql as $row) {
				echo '<div class="col-lg-3 item-person-in-list" id="photo_'.$row['id'] .'">';
				echo '<div class="clearfix btn-remove" style="display:none"><button class="btn btn-mini btn-primary" onclick="remove_photo('.$row['id'].')"> <i class="icon-trash"></i> Remove this photo</button></div>'; 
				echo '<div class="thumbnail" style="overflow:hidden; height:220px"><a href="javascript:void(0)" onclick="getPhotoComment('.$row['id'].','.$person_id.')"><img src="'.base_url().$row['photo'].'" alt="" ></a></div></div>';
			}

			echo '<script type="text/javascript">$(document).ready(function() {$(".item-person-in-list").hover(function(){$(this).children("div.btn-remove").show()}, function(){$(this).children("div.btn-remove").hide()})  });</script>'; 
		} else {
			echo "<p>No photo from now</p>";
		}
	}

	public function loadAllListPhotoPerson(){
		$person_id = (int)$this->input->post('personId');
		$memId = $this->session->userdata('sess_memId');
		$sql = $this->db->select('id,photo')->get_where('photo_person', array('person_id' => $person_id))->result_array();

		if(count($sql)) {
			foreach($sql as $row) {
				echo '<div class="col-lg-3 item-person-in-list" id="photo_'.$row['id'] .'">';
				echo '<div class="clearfix btn-remove" style="display:none"><button class="btn btn-mini btn-primary" onclick="remove_photo('.$row['id'].')"> <i class="icon-trash"></i> Remove this photo</button></div>'; 
				echo '<div class="thumbnail" style="overflow:hidden; height:220px"><a href="javascript:void(0)" onclick="getPhotoComment('.$row['id'].','.$person_id.')"><img src="'.base_url().$row['photo'].'" alt="" ></a></div></div>';
			}

		} else {
			echo "<p>No photo from now</p>";
		}
	}

	public function post_comment() {
		$memId = (int)$this->input->post('memId');
		$memAvatar = $this->input->post('memAvatar');
		$personId = (int)$this->input->post('personId');
		$comment = nl2br($this->input->post('comment'));
		$arr = array(
			'memId'	=> $memId,
			'memName' => $this->session->userdata('sess_fullname'),
			'mem_avatar' => $memAvatar,
			'personId' => $personId,
			'comment' => $comment,
			'time_added' => time()
		);

		if($this->db->insert('comment', $arr)) {
			$info = array('status' => TRUE);
		} else {
			$info = array('status' => FALSE, 'message' => 'Posting is faild');
		}

		echo json_encode($info);
	}

	public function get_comment() {
		$person_id = (int)$this->input->post('personId');
		$sesMem = $this->session->userdata('sess_memId');
		$this->db->order_by('id', 'desc');
		$this->db->limit(4);
		$sql = $this->db->get_where('comment', array('personId' => $person_id))->result_array();

		if(count($sql)) {
			foreach($sql as $row) {
				if($row['mem_avatar'] != '') {
					$avatar = '<img src="'. base_url() . $row['mem_avatar'] .'" alt="">';
				} else {
					$avatar = '<img src="'. base_url() .'public/image/NoImage.jpg" alt="">';
				}
				$timeago = $this->util->time_elapsed_string($row['time_added']);
				$totalDislike = $this->total_dislike_comment($row['id']);
				$totaLike = $this->total_like_comment($row['id']);

				echo '<div class="row" style="padding-top:20px"><div class="col-lg-1"><div class="thumbnail" style="width:60px; height:50px; overflow:hidden">'. $avatar;  
				echo '</div></div><div class="col-lg-9">';
				echo '<p>';
				echo '<span><b><a href="">'.$row['memName'].'</b></a></span>';
				echo '<span class="hour_ago_comment"> '. $timeago .'</span>';
				echo '</p>';
				echo '<p>';
				echo $row['comment'];		
				echo '</p>';
				echo '<p>';
				echo '<a href="javascript:void(0)"><i id="like_comment_person_'.$row['id'].'" style="font-weight:bold; font-size:12px;">'.$totaLike.'</i> <i class="icon-thumbs-up" onclick="like_comment_person('.$sesMem.','.$row['id'].')"></i></a> <a href="javascript:void(0)"><i class="icon-thumbs-down" onclick="dislike_comment_person('.$sesMem.','.$row['id'].')"></i> <i id="dislike_comment_person_'.$row['id'].'" style="font-weight:bold; font-size:12px;">'.$totalDislike.'</i></a>';
				echo '</p></div></div>';
			}
		} else {
			//echo "<p>No image from now</p>";
		}	
	}

	public function total_dislike_comment($c_id){
		$total = $this->db->query("SELECT SUM(dislike) as total FROM like_comment WHERE commentId =".$c_id)->row();
		if($total->total > 0) {
			return $total->total;
		} else {
			return "";
		}
	}
	public function total_like_comment($c_id){
		$total = $this->db->query("SELECT SUM(`like`) as total FROM like_comment WHERE commentId =".$c_id)->row();
		if($total->total > 0) {
			return $total->total;
		} else {
			return "";
		}
	}

	public function total_comment($type  = 'like', $c_id){
		if($type == 'like') {
			$total = $this->db->query("SELECT SUM(`like`) as total FROM like_video WHERE videoId =".$c_id)->row();	
		} else {
			$total = $this->db->query("SELECT SUM(`dislike`) as total FROM like_video WHERE videoId =".$c_id)->row();
		}
		
		if($total->total > 0) {
			return $total->total;
		} else {
			return "";
		}
	}

	/*** GEt total comment via Ajax **/
	public function getTotalLikeCm(){
		$c_id = (int)$this->input->post('cmId');
		$total = $this->db->query("SELECT SUM(`like`) as total FROM like_comment WHERE commentId =".$c_id)->row();
		if($total->total > 0) {
			echo  number_format($total->total, '0', '', ',');
		} else {
			echo "";
		}
	}

	public function getTotalDislikeLikeCm(){
		$c_id = (int)$this->input->post('cmId');
		$total = $this->db->query("SELECT SUM(`dislike`) as total FROM like_comment WHERE commentId =".$c_id)->row();
		if($total->total > 0) {
			echo  number_format($total->total, '0', '', ',');
		} else {
			echo "";
		}
	}


	public function get_more_comment() {
		$person_id = (int)$this->input->post('personId');
		$sesMem = $this->session->userdata('sess_memId');
		$start = (int)$this->input->post('start');
		$this->db->order_by('id', 'desc');
		$this->db->limit(4, $start);
		$sql = $this->db->get_where('comment', array('personId' => $person_id))->result_array();

		if(count($sql)) {
			foreach($sql as $row) {
				if($row['mem_avatar'] != '') {
					$avatar = '<img src="'. base_url() . $row['mem_avatar'] .'" alt="">';
				} else {
					$avatar = '<img src="'. base_url() .'public/image/NoImage.jpg" alt="">';
				}
				$timeago = $this->util->time_elapsed_string($row['time_added']);
				$totalDislike = $this->total_dislike_comment($row['id']);
				$totaLike = $this->total_like_comment($row['id']);

				echo '<div class="row" style="padding-top:20px"><div class="col-lg-1"><div class="thumbnail" style="width:60px; height:50px">'. $avatar;  
				echo '</div></div><div class="col-lg-9">';
				echo '<p>';
				echo '<span><b><a href="">'.$row['memName'].'</b></a></span>';
				echo '<span class="hour_ago_comment"> '. $timeago .'</span>';
				echo '</p>';
				echo '<p>';
				echo $row['comment'];    		
				echo '</p>';
				echo '<p>';
				echo '<a href="javascript:void(0)"><i id="like_comment_person_'.$row['id'].'" style="font-weight:bold; font-size:12px;">'.$totaLike.'</i> <i class="icon-thumbs-up" onclick="like_comment_person('.$sesMem.','.$row['id'].')"></i></a> <a href="javascript:void(0)"><i class="icon-thumbs-down" onclick="dislike_comment_person('.$sesMem.','.$row['id'].')"></i> <i id="dislike_comment_person_'.$row['id'].'" style="font-weight:bold; font-size:12px;">'.$totalDislike.'</i></a>';
				echo '</p></div></div>';
			}
		} else {
			//echo "<p>No image from now</p>";
		}	
	}

	public function add_subscribed() {
		$memId = (int)$this->input->post('memId');
		$personId = (int)$this->input->post('personId');
		if($this->db->insert('respected_for_people', array('memId' => $memId, 'personId' => $personId))) {
			$info = array('status' => TRUE);
		} else {
			$info = array('status' => FALSE, 'message' => 'Can not handle this function');
		}
		echo json_encode($info);
	}

	public function check_status_subscribed() {
		$memId = (int)$this->input->post('memId');
		$personId = (int)$this->input->post('personId');
		$ok = array();

		$check = $this->db->select('memId')->get_where('respected_for_people', array('personId' => $personId))->result_array();
		if(count($check)) {
			foreach($check as $item) {
				$ok[] = $item['memId'];
			}
			if(in_array($memId, $ok)) {
				$info = array('status' => TRUE);
			} else {
				$info = array('status' => FALSE);	
			}
		} else {
			$info = array('status' => FALSE);
		}
		echo json_encode($info);
		// $check = $this->db->select('memId')->get_where('respected_for_people', array('personId' => 9))->result_array();
		// $ok = array();
		// foreach($check as $item) {
		// 	$ok[] = $item['memId'];
		// }
		// print_r($ok);
	}

	public function load_total_subscribed() {
		$personId = (int)$this->input->post('personId');
		$total = $this->db->select('id')->get_where('respected_for_people', array('personId' => $personId));
		$totals = $total->num_rows();
		$num = number_format($totals, '0', '', ',');

		echo json_encode(array('total' => $num));
	}

	public function load_total_comment() {
		$personId = (int)$this->input->post('personId');
		$total = $this->db->select('id')->get_where('comment', array('personId' => $personId));
		$totals = $total->num_rows();
		//$num = number_format($totals, '0', '', ',');

		echo json_encode(array('total' => $totals));
	}

	public function load_video() {
		$personId = (int)$this->input->post('personId');
		$sesMem = $this->session->userdata('sess_memId');
		$this->db->order_by('like', 'desc');
		$this->db->limit(3);
		$sql = $this->db->get_where('person_video', array('personId' => $personId))->result_array();
		if(count($sql)) {
			foreach($sql as $row) {

				echo '<div class="col-lg-4">';
				echo '<div class="row"><div class="col-lg-12">';  
				echo '<object width="100%" height="315"><param name="movie" value="'.$row['url_video'].'"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="'.$row['url_video'].'" type="application/x-shockwave-flash" width="100%" height="315" allowscriptaccess="always" allowfullscreen="true"></embed></object>';
				echo '</div></div>';
			?>
				<div class="row"><div class="col-lg-12" style="font-size:20px"><a href="javascript:void(0)"><i id="like_video_<?=$row['id']?>"><?=$this->total_comment('like', $row['id'])?></i> <i class="icon-thumbs-up" onclick=like_video('<?=$sesMem?>','<?=$row['id']?>','like')></i></a> <a href="javascript:void(0)"><i class="icon-thumbs-down" onclick="like_video('<?=$sesMem?>','<?=$row['id']?>', 'dislike')"></i> <i id="dislike_video_<?=$row['id']?>"><?=$this->total_comment('dislike', $row['id'])?></i></a></div></div>
			<?php 
				echo '</div>';
				
			}
		} else {
			//echo "<p>No image from now</p>";
		}	
	}

	public function add_video() {
		$video = str_replace("watch?v=", "v/", $this->input->post('url_video'));
		$arr = array(
			'memId'	=> (int)$this->input->post('memId'),
			'personId' => (int)$this->input->post('personId'),
			'url_video' => trim($video),
			'date_added' => time()
		);

		if($this->db->insert('person_video', $arr)) {
			$info = array('status' => TRUE);
		} else {
			$info = array('status' => FALSE);
		}
		echo json_encode($info);
	}

	public function get_more_video() {
		$person_id = (int)$this->input->post('personId');
		$start = (int)$this->input->post('start');
		$this->db->order_by('like', 'desc');
		$this->db->limit(3, $start);
		$sql = $this->db->get_where('person_video', array('personId' => $person_id))->result_array();
		
		

		if(count($sql)) {
			foreach($sql as $row) {

				echo '<div class="col-lg-4">';
				echo '<div class="row"><div class="col-lg-12">';  
				echo '<iframe width="100%" height="315" src="//www.youtube.com/embed/'. $row['url_video'].'?rel=0" frameborder="0" allowfullscreen></iframe>';
				echo '</div></div>';
				echo '<div class="row"><div class="col-lg-12" style="font-size:20px"><a href="javascript:void(0)"><i id="like_video_'.$row['id'].'"></i><i class="icon-thumbs-up" onclick="like_video('.$sesMem.','.$row['id'].')"></i></a> <a href="javascript:void(0)"><i id="dislike_video_'.$row['id'].'"></i><i class="icon-thumbs-down" onclick="dislike_video('.$sesMem.','.$row['id'].')"></i></a></div></div>';
				echo '</div>';
				
			}
		} else {
			//echo "<p>No image from now</p>";
		}
	}

	public function like_video(){
	
		$memId = (int)$this->input->post('memId');
		$videoId = (int)$this->input->post('videoId');
		$type = $this->input->post('type');
		if($type == 'like') {
			$arr_update = array(
				'memId'	=> $memId,
				'videoId' => $videoId,
				'like'=> 1
			);
			$sql = $this->db->select('id')->get_where('like_video', array('memId' => $memId, 'videoId' => $videoId, 'like' => 1));
		} else {
			$arr_update = array(
				'memId'	=> $memId,
				'videoId' => $videoId,
				'dislike'=> 1
			);
			$sql = $this->db->select('id')->get_where('like_video', array('memId' => $memId, 'videoId' => $videoId, 'dislike' => 1));	
		}

		//Check that this user has been like for this person
		
		if($sql->num_rows() > 0 ) {
			$info = array('status' => FALSE, 'message' => 'Like is faild');	
		} else {
			$this->db->insert('like_video', $arr_update);
			$info = array('status' => TRUE, 'message' => 'OK');	
		}
		
		echo json_encode($info);
		
	}
	
	// public function dislike_video(){
	
	// 	$memId = (int)$this->input->post('memId');
	// 	$videoId = (int)$this->input->post('videoId');
		
	// 	$arr = array(
	// 		'memId'	=> (int)$this->input->post('memId'),
	// 		'videoId' => (int)$this->input->post('videoId')
	// 	);
	// 	$arr_update = array(
	// 		'memId'	=> (int)$this->input->post('memId'),
	// 		'videoId' => (int)$this->input->post('videoId'),
	// 		'dislike'=> 1
	// 	);
	// 	$check = $this->db->select('id')->get_where('like_video', $arr);
	// 	if($check->num_rows() > 0 ) {  
	// 		$sql = $this->db->select('id')->get_where('like_video', $arr)->row();
			
	// 		$update = $this->db->update('like_video', $arr_update, array('id' => $sql->id));
	// 		if($update){
	// 			$info = array('status' => TRUE, 'message' => 'Dislike this video is successfull.');
	// 		}else{
	// 			$info = array('status' => FALSE, 'message' => 'Dislike is faild');
	// 		}
	// 	}	else {
	// 		if($this->db->insert('like_video', $arr_update)) {
	// 			$info = array('status' => TRUE, 'message' => 'Dislike this video is successfull.');
	// 		} else {
	// 			$info = array('status' => FALSE, 'message' => 'Dislike is faild');
	// 		}
	// 	}
		
	// 	echo json_encode($info);
		
	// }  
	
	public function load_total_like_video() {
		$videoId = (int)$this->input->post('videoId');
		$type = $this->input->post('type');
		if($type == 'like') {
			$total = $this->db->query("SELECT SUM(`like`) as total FROM like_video WHERE videoId =".$videoId)->row();
		} else {
			$total = $this->db->query("SELECT SUM(`dislike`) as total FROM like_video WHERE videoId =".$videoId)->row();	
		}

		if($total->total > 0) {
			echo  number_format($total->total, '0', '', ',');
		} else {
			echo "";
		}
	}
	
	// public function load_total_dislike_video() {
	// 	$videoId = (int)$this->input->post('videoId');
	// 	$total = $this->db->select('id')->get_where('like_video', array('videoId' => $videoId, 'dislike' => 1));
	// 	$totals = $total->num_rows();
	// 	$num = number_format($totals, '0', '', ',');

	// 	echo json_encode(array('total' => $num));
	// } 
	
	/**************************Like comment person**********************************/
	
	public function like_comment_person(){ 
	
		$memId = (int)$this->input->post('memId');
		$commentId = (int)$this->input->post('commentId');
		$arr_update = array(
		 	'memId'	=> $memId,
		 	'commentId' => $commentId,
		 	'like'=> 1
		);
		//Check that this user has been like for this person
		$sql = $this->db->select('id')->get_where('like_comment', array('memId' => $memId, 'commentId' => $commentId, 'like' => 1));
		if($sql->num_rows() > 0 ) {
			$info = array('status' => FALSE, 'message' => 'Like is faild');	
		} else {
			$this->db->insert('like_comment', $arr_update);
			$info = array('status' => TRUE, 'message' => 'OK');	
		}

		
		echo json_encode($info);
		
	}
	
	public function dislike_comment_person(){
	
		$memId = (int)$this->input->post('memId');
		$commentId = (int)$this->input->post('commentId');
		
		$arr_update = array(
		 	'memId'	=> $memId,
		 	'commentId' => $commentId,
		 	'dislike'=> 1
		);
		//Check that this user has been like for this person
		$sql = $this->db->select('id')->get_where('like_comment', array('memId' => $memId, 'commentId' => $commentId, 'dislike' => 1));
		if($sql->num_rows() > 0 ) {
			$info = array('status' => FALSE, 'message' => 'Like is faild');	
		} else {
			$this->db->insert('like_comment', $arr_update);
			$info = array('status' => TRUE, 'message' => 'OK');	
		}
		
		echo json_encode($info);
		
	} 
	
	public function getPhotoComment(){
		
		$photoId = (int)$this->input->post('photoId');
		$personId = (int)$this->input->post('personId'); 
		$memAvatar = $this->session->userdata('sess_memAvatar');
		$sesMem = $this->session->userdata('sess_memId'); 
		//Load Photo
		
		$infoPhoto = $this->db->select('mem_id,person_id, photo, id')->get_where('photo_person', array('id' => $photoId,'person_id' => $personId))->row_array();
		$prev = $this->db->select('id')->get_where('photo_person', array('id <' => $photoId,'person_id' => $personId),1,'ODER BY id DESC')->row_array();
		$next = $this->db->select('id')->get_where('photo_person', array('id >' => $photoId,'person_id' => $personId),1,'ODER BY id ASC')->row_array(); 
		
		$nameWhoUpload = $this->member_model->get_name($infoPhoto['mem_id']);
		$nameOfPerson = $this->person_model->get_name_person($infoPhoto['person_id']);
		$titleShare = 'Photo of ' . $nameOfPerson.'on Death site';

		$prevbtn = ($prev) ? '<div class="preview_prev" onclick="getPhotoComment('.$prev['id'].','.$personId.')"><img src="' . base_url() . 'public/image/prev_38x62.png" alt="prev" /></div>' : '';
		$nextbtn = ($next) ? '<div class="preview_next" onclick="getPhotoComment('.$next['id'].','.$personId.')"><img src="' . base_url() . 'public/image/next_38x62.png" alt="next" /></div>' : '';
		$imageLink = base_url(). $infoPhoto['photo'];
		$fb_link = 'http://www.facebook.com/sharer.php?u='.base_url().'photo_share/index/'.$infoPhoto['id'];

		$dataImage = '<div class="row" style="padding-top:5px;"><div class="col-lg-6 social">';
		$dataImage .='<a title="Share to facebook" target="_blank" href="'.$fb_link.'"><i class="icon-facebook-sign"></i></a>';
		$dataImage .='<a href="https://twitter.com/intent/tweet?original_referer='.$imageLink.'&text='.$titleShare.'&tw_p=tweetbutton&url='.$imageLink.'" onclick="javascript:window.open(this.href,"", "menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=600,width=600");return false;" title="Share on Twitter" target="_blank"><i class="icon-twitter"></i>	</a>';
		$dataImage .='<a target="_blank" title="Share to Pinterest" href="//pinterest.com/pin/create/button/?url='.base_url().'photo_share/index/'.$infoPhoto['id'].'&media='.$imageLink.'&description='.$titleShare.'" data-pin-do="buttonPin" data-pin-config="above"><i class="icon-pinterest"></i></a></div>';
    $dataImage .='<div class="col-lg-6" style="color:#999; text-align:left; padding-top:5px">Uploaded by '.$nameWhoUpload.'</div>';

		$dataImage .='</div>';
		$dataImage .='<img class="commentImg" src="' . base_url() . $infoPhoto['photo'] .'">' . $prevbtn . $nextbtn ;
		

		$dataComment='<div class="col-lg-12">
		            		<textarea placeholder="Leave a comment" id="txt_commentPhoto" class="form-control" rows="2"></textarea>
		            	</div>
						<div class="col-lg-12" style="text-align:right;">
							<a href="javascript:void(0)" onclick="post_commentPhoto('.$sesMem.', \''.$memAvatar.'\', '.$photoId.')" id="btn_post_commentPhoto" style="margin-top:10px;" class="btn btn-primary btn-xs">Add Comment</a>
						</div>
						<div class="col-lg-12" id="loading_list_photo" style="text-align:center; padding-top:50px; display:none">
							<img src="' . base_url() . 'public/image/ajax-loader.gif" alt="">
						</div>
						<div class="col-lg-12" id="show-list-commentPhoto"></div>
					';
		
		
		echo json_encode(
			array(
				'status' => TRUE,
				'dataImage' => $dataImage,
				'dataComment' => $dataComment
			)
		);
		
	}
	
	public function post_commentPhoto() {
	
		$memId = (int)$this->input->post('memId');
		$photoId = (int)$this->input->post('photoId');
		$mem_avatar = $this->input->post('memAvatar');
		$comment = nl2br($this->input->post('commentPhoto'));
		$arr = array(
			'memId'	=> $memId,
			'memName' => $this->session->userdata('sess_fullname'), 
			'photoId' => $photoId,
			'mem_avatar' => $mem_avatar,
			'comment' => $comment,
			'time_added' => time()
		);

		if($this->db->insert('comment_photo', $arr)) {
			$info = array('status' => TRUE);
		} else {
			$info = array('status' => FALSE, 'message' => 'Posting is faild');
		}

		echo json_encode($info);
		
	}
	
	public function getCommentPhoto() {
		$photoId = (int)$this->input->post('photoId');
		$this->db->order_by('id', 'desc');
		//$this->db->limit(4);
		$sql = $this->db->get_where('comment_photo', array('photoId' => $photoId))->result_array();

		if(count($sql)) {
			foreach($sql as $row) {
				if($row['mem_avatar'] !== '') {
					$avatar = '<img src="'. base_url() . $row['mem_avatar'] .'" alt="">';
				} else {
					$avatar = '<img src="'. base_url() .'public/image/NoImage.jpg" alt="">';
				}
				$timeago = $this->util->time_elapsed_string($row['time_added']);

				echo '<div class="row" style="padding-top:20px"><div class="col-lg-3"><div class="thumbnail">'. $avatar;  
				echo '</div></div><div class="col-lg-9">';
				echo '<p>';
				echo '<span><b><a href="">'.$row['memName'].'</b></a></span>';
				echo '<span class="hour_ago_comment"> '. $timeago .'</span>';
				echo '</p>';
				echo '<p>';
				echo $row['comment'];    		
				echo '</p>';
				echo '<p>';
				//echo '<a href="#"><i id="like_comment_photo_'.$row['id'].'"></i><i class="icon-thumbs-up" onclick="like_comment_photo('.$row['id'].')"></i></a> <a href="#"><i id="dislike_comment_photo_'.$row['id'].'"></i><i class="icon-thumbs-down" onclick="dislike_comment_photo('.$row['id'].')"></i></a>';
				echo '</p></div></div>';
			}
		} else {
			//echo "<p>No image from now</p>";
		}	
	}
	
	public function remove_photo(){
		$id = (int)$this->input->post('id');
		$sql = $this->db->select('photo')->get_where('photo_person', array('id' => $id))->row_array();
		$photo  = $sql['photo'];
		@unlink($photo);
		if($this->db->delete('photo_person', array('id' => $id))) {
			$info = array('status' => TRUE);
		} else {
			$info = array('status' => FALSE, 'message' => 'Error');
		}

		echo json_encode($info);
	}


	/** Function get list photo of each person
	* Return list photos
	**/
	public function photo() {
		if(!$this->session->userdata('loginStatus')) redirect('landing');
		$uri = $this->uri->segment(2);
		$infoPerson = $this->person_model->get_person($uri);

		$this->current_person_id = $uri;
		$this->show_btn_upload = FALSE;

		$this->template->title('Photo of '.$infoPerson['name'], $this->config->item('site_name'))
			->set_metadata('keywords', $infoPerson['name'])
            ->set_metadata('description', $infoPerson['name'])
			->set('infoPerson', $infoPerson)
			->build('person/photo');	
	}

	public function invite() {
		$memName = $this->session->userdata('sess_fullname');
		$url_invite = $this->input->post('url_invite');
		$email_invite = $this->input->post('email');

		$this->loadMail();
	    $this->email->from("tinapc@gmail.com", "The mail invitation for you to visit one of links on site Dead");
	    $this->email->to($email_invite);
	    $this->email->subject('The mail invitation for you to visit one of links on site Dead');
	    $this->email->message($this->load->view('person/invite', array('url_invite' => $url_invite, 'memName' => $memName),TRUE));
	    $this->email->set_newline("\r\n");	
	    if($this->email->send()) {
	    	$info = array('status' => TRUE, 'message' => 'Your request has been successfully');
	    } else {
	    	$info = array('status' => FALSE, 'message' => 'Faild');
	    }

	    echo json_encode($info);
	}
	
	public function account() { 
		if(!$this->session->userdata('loginStatus')) redirect('landing');
		
		$oldImage = $this->input->post('old_photo');
		
		$this->template->set_layout('default'); 

		if($_POST) { 

				if(!empty($_FILES['avatar']['name']))
                { 
                    $config['upload_path'] = './data_uploads/avatar/';
                    $config['allowed_types'] = 'gif|jpg|png';
                    $config['encrypt_name'] = TRUE;

                    $this->load->library('upload', $config);

                    if ( ! $this->upload->do_upload('avatar'))
                    {
                        echo $this->upload->display_errors();
                        $image = $oldImage;
                    } else {
                    	if($oldImage !== "") @unlink($oldImage);
                        $up = $this->upload->data();
                        $image = 'data_uploads/avatar/' . $up['file_name'];

                        $imageWidth = $up['image_width'];
                        if($imageWidth > 150)
                        {
                            $this->load->library('image_lib');
                            $config['image_library'] = 'GD2';
                            $config['source_image'] = $up['full_path'];
                            $config['quality'] = 75;
                            $config['maintain_ratio'] = TRUE;
                            $config['master_dim'] = 'auto';
                            $config['width'] = 150;
                            $config['height'] = 150;

                            $this->image_lib->initialize($config);
                            $this->image_lib->resize();
                        }

                    }
                } else {
                    $image = $oldImage;
                }

				$fullname = $this->input->post('fullname');
				$email = $this->input->post('email');
				if($this->input->post('password') != "") {
					$password = md5(md5($this->input->post('password')));	
				} else {
					$password = $this->input->post('old_pass');	
				}
				$id = (int)$this->session->userdata('sess_memId');
				$arr = array( 
					'fullname' => $fullname,
					//'email'			=> $this->input->post('email'), 
					'password'		=> $password,
					'avatar'		=> $image
				);

				$this->db->update('member', $arr, array('id' => $id));
				
				$this->session->set_flashdata('sess_Info', 'The member has been updated successfully');
				redirect('account'); 
	
		}

		$memId = $this->session->userdata('sess_memId');
		$infoMember = $this->db->get_where('member', array('id' => $memId))->row();
		$this->template->title('Account manager')->set('infoMember', $infoMember)->build('person/account');	
	}

	/** Report for person if this is bad **/
	public function report() {
		$personId = (int)$this->input->post('personId');
		$type = (int)$this->input->post('type');
		if($this->db->update('person', array('bad' => $type), array('id' => $personId))) {
			$info = array('status' => TRUE, 'message' => 'Your report has been successful');
		} else {
			$info = array('status' => FALSE);
		}

		echo json_encode($info);
	}

	public function message(){
		$data['meid'] = (int)$this->input->get('meid');
		$data['meName'] = $this->input->get('meName');
		$data['who'] = (int)$this->input->get('who');
		$this->load->view('person/message', $data);
	}

	public function add_msg(){
		$arr = array(
			'sender_id' => (int)$this->session->userdata('sess_memId'),
			'sender_name' => $this->session->userdata('sess_fullname'),
			'to_who' => (int)$this->input->post('who_id'),
			'title'	=> $this->input->post('subject'),
			'msg' => nl2br($this->input->post('msg')),
			'date_added' => time(),
			'status'	=> '0'
		);

		if($this->db->insert('message', $arr)) {
			$info = array('status' => TRUE, 'message' => 'Your request has been successful');
		} else {
			$info = array('status' => FALSE, 'message' => 'We had an error');
		}

		echo json_encode($info);
	}

	public function photo_share(){
		$id = $this->uri->segment(3);
		$sql = $this->db->get_where('photo_person', array('id' => $id))->row();
		$namePerson = $this->person_model->get_name_person($sql->person_id);
		$this->load->view('person/photo_share', array('infoPhoto' => $sql, 'namePerson' => $namePerson));
	}

}